import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:katana_router/katana_router.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/toolkit/utilities/app_constants.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/common_utils.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

part 'upload_dynamic_production.page.dart';

/// 上传动态页面
@PagePath('/upload-dynamic')
class UploadDynamicProduction extends StatefulWidget {
  const UploadDynamicProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$UploadDynamicProductionQuery().call();

  @override
  State<UploadDynamicProduction> createState() =>
      _UploadDynamicProductionState();
}

class _UploadDynamicProductionState extends State<UploadDynamicProduction> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();

  List<AssetEntity> _selectedAssets = [];
  String? _mediaType; // 'image' or 'video'
  bool _isPublishing = false;

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _renderHeader(context),

              // 内容区域
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 20.h),

                      // 主容器：包含标题、内容、媒体选择
                      _renderMainContainer(),

                      SizedBox(height: 80.h),

                      GestureDetector(
                        onTap: () {
                          CommonUtils.launchUrl(ProjectConstants.eulaUrl);
                        },
                        child: SizedBox(
                          width: 390,
                          child: Text(
                            'EULA',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: 12.sp,
                              fontFamily:
                                  GoogleFonts.arimo(
                                    fontWeight: FontWeight.w700,
                                  ).fontFamily,
                              fontWeight: FontWeight.w700,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 渲染顶部导航栏
  Widget _renderHeader(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.white.withValues(alpha: 0.5),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.arrow_back_rounded,
                color: ColorPalette.black,
                size: 24.sp,
              ),
            ),
          ),
          const Spacer(),
          // 发布按钮
          GestureDetector(
            onTap: _isPublishing ? null : () => _handlePublish(context),
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 22.w, vertical: 7.h),
              decoration: BoxDecoration(
                color: ColorPalette.blue1,
                borderRadius: BorderRadius.circular(26.r),
              ),
              child: Text(
                _isPublishing ? 'Publishing...' : 'Publish',
                style: TextStyle(fontSize: 16.sp, color: ColorPalette.white),
              ).carterOne(weight: FontWeight.w400),
            ),
          ),
        ],
      ),
    );
  }

  /// 渲染主容器
  Widget _renderMainContainer() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 26.h),
      decoration: BoxDecoration(
        color: ColorPalette.white,
        borderRadius: BorderRadius.circular(26.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题输入框
          TextField(
            controller: _titleController,
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
              hintText: 'Enter Your Title Now',
              hintStyle: TextStyle(
                fontSize: 16.sp,
                color: ColorPalette.black,
                fontFamily:
                    GoogleFonts.arimo(fontWeight: FontWeight.w400).fontFamily,
              ),
              border: InputBorder.none,
            ),
            style: TextStyle(
              fontSize: 16.sp,
              color: ColorPalette.black,
              fontFamily:
                  GoogleFonts.arimo(fontWeight: FontWeight.w400).fontFamily,
            ),
          ),

          Divider(color: ColorPalette.blue3.withValues(alpha: 0.5)),

          // 内容输入框
          TextField(
            controller: _contentController,
            maxLines: 6,
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
              hintText: 'Come and post your latest updates~',
              hintStyle: TextStyle(
                fontSize: 14.sp,
                color: ColorPalette.black.withValues(alpha: 0.4),
                fontFamily:
                    GoogleFonts.arimo(fontWeight: FontWeight.w400).fontFamily,
              ),
              border: InputBorder.none,
            ),
            style: TextStyle(
              fontSize: 14.sp,
              color: ColorPalette.black,
              fontWeight: FontWeight.w400,
              fontFamily:
                  GoogleFonts.arimo(fontWeight: FontWeight.w400).fontFamily,
            ),
          ),

          SizedBox(height: 16.h),

          // 媒体选择区域
          SizedBox(
            height: 98.w,
            child:
                _selectedAssets.isEmpty
                    ? GestureDetector(
                      onTap: _showMediaPickerDialog,
                      child: Container(
                        width: 98.w,
                        height: 98.w,
                        decoration: BoxDecoration(
                          color: ColorPalette.black.withValues(alpha: 0.05),
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Icon(
                          Icons.camera_alt_outlined,
                          size: 36.sp,
                          color: ColorPalette.black.withValues(alpha: 0.6),
                        ),
                      ),
                    )
                    : ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: _selectedAssets.length + 1,
                      itemBuilder: (context, index) {
                        if (index == _selectedAssets.length) {
                          return Padding(
                            padding: EdgeInsets.only(left: 12.w),
                            child: GestureDetector(
                              onTap: _showMediaPickerDialog,
                              child: Container(
                                width: 98.w,
                                height: 98.w,
                                decoration: BoxDecoration(
                                  color: ColorPalette.black.withValues(
                                    alpha: 0.05,
                                  ),
                                  borderRadius: BorderRadius.circular(12.r),
                                ),
                                child: Icon(
                                  Icons.camera_alt_outlined,
                                  size: 36.sp,
                                  color: ColorPalette.black.withValues(
                                    alpha: 0.6,
                                  ),
                                ),
                              ),
                            ),
                          );
                        }
                        return Padding(
                          padding: EdgeInsets.only(left: index == 0 ? 0 : 12.w),
                          child: _buildMediaThumbnail(
                            _selectedAssets[index],
                            index,
                          ),
                        );
                      },
                    ),
          ),
        ],
      ),
    );
  }

  /// 显示媒体选择对话框
  Future<void> _showMediaPickerDialog() async {
    // 如果已经有选中的媒体，直接添加
    if (_selectedAssets.isNotEmpty) {
      await _handlePickMedia(
        _mediaType == 'image' ? RequestType.image : RequestType.video,
      );
      return;
    }

    // 显示选择对话框
    final choice = await showModalBottomSheet<String>(
      context: context,
      backgroundColor: Colors.transparent,
      builder:
          (context) => Container(
            decoration: BoxDecoration(
              color: ColorPalette.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.r),
                topRight: Radius.circular(20.r),
              ),
            ),
            child: SafeArea(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 12.h),
                    width: 40.w,
                    height: 4.h,
                    decoration: BoxDecoration(
                      color: ColorPalette.black.withValues(alpha: 0.2),
                      borderRadius: BorderRadius.circular(2.r),
                    ),
                  ),
                  SizedBox(height: 20.h),
                  GestureDetector(
                    onTap: () => Navigator.pop(context, 'image'),
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 16.h,
                      ),
                      child: Row(
                        children: [
                          Icon(
                            Icons.image,
                            color: ColorPalette.black,
                            size: 24.sp,
                          ),
                          SizedBox(width: 16.w),
                          Text(
                            'Select Photos',
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: ColorPalette.black,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Divider(),
                  GestureDetector(
                    onTap: () => Navigator.pop(context, 'video'),
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 16.h,
                      ),
                      child: Row(
                        children: [
                          Icon(
                            Icons.videocam,
                            color: ColorPalette.black,
                            size: 24.sp,
                          ),
                          SizedBox(width: 16.w),
                          Text(
                            'Select Videos',
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: ColorPalette.black,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 40.h),
                ],
              ),
            ),
          ),
    );

    if (choice != null) {
      await _handlePickMedia(
        choice == 'image' ? RequestType.image : RequestType.video,
      );
    }
  }

  /// 构建媒体缩略图
  Widget _buildMediaThumbnail(AssetEntity asset, int index) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Container(
          width: 98.w,
          height: 98.w,
          decoration: BoxDecoration(
            color: ColorPalette.white,
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: FutureBuilder<String?>(
              future: _getAssetThumbnail(asset),
              builder: (context, snapshot) {
                if (snapshot.hasData && snapshot.data != null) {
                  return Image.file(File(snapshot.data!), fit: BoxFit.cover);
                }
                return Container(
                  color: ColorPalette.black.withValues(alpha: 0.1),
                  child: Center(child: CircularProgressIndicator()),
                );
              },
            ),
          ),
        ),
        // 删除按钮
        Positioned(
          top: 0.w,
          right: -8.w,
          child: GestureDetector(
            onTap: () => _removeAsset(index),
            child: Container(
              width: 24.w,
              height: 24.w,
              decoration: BoxDecoration(
                color: ColorPalette.red,
                shape: BoxShape.circle,
                border: Border.all(color: ColorPalette.white, width: 2.w),
              ),
              child: Icon(Icons.close, size: 16.sp, color: ColorPalette.white),
            ),
          ),
        ),
        // 视频标识
        if (_mediaType == 'video')
          Positioned.fill(
            child: Center(
              child: Icon(
                Icons.play_arrow,
                color: ColorPalette.white,
                size: 36.sp,
              ),
            ),
          ),
      ],
    );
  }

  /// 获取 Asset 对应的文件（用于发布时复制文件）
  // ignore: unused_element
  Future<File?> _getAssetFile(AssetEntity asset) async {
    try {
      return await asset.file;
    } catch (e) {
      return null;
    }
  }

  /// 获取资源缩略图路径（图片直接返回，视频生成缩略图）
  Future<String?> _getAssetThumbnail(AssetEntity asset) async {
    try {
      if (asset.type == AssetType.image) {
        // 图片直接返回文件路径
        final file = await asset.file;
        return file?.path;
      } else if (asset.type == AssetType.video) {
        // 视频需要生成缩略图
        final file = await asset.file;
        if (file != null) {
          final thumbnail = await VideoThumbnail.thumbnailFile(
            video: file.path,
            imageFormat: ImageFormat.PNG,
            maxWidth: 400,
            quality: 75,
          );
          return thumbnail;
        }
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  /// 处理选择媒体
  Future<void> _handlePickMedia(RequestType requestType) async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 9,
          selectedAssets: _selectedAssets,
          requestType: requestType,
        ),
      );

      if (result != null && result.isNotEmpty) {
        // 确定媒体类型
        final asset = result.first;
        final isImage = asset.type == AssetType.image;

        // 验证：如果选择的是图片，确保所有都是图片；如果是视频，确保所有都是视频
        final allSameType = result.every(
          (a) =>
              (isImage && a.type == AssetType.image) ||
              (!isImage && a.type == AssetType.video),
        );

        if (!allSameType) {
          StageWhisper.lament('Please select either all images or all videos');
          return;
        }

        setState(() {
          if (_mediaType == null) {
            _selectedAssets = result;
            _mediaType = isImage ? 'image' : 'video';
          } else {
            // 追加到现有列表
            _selectedAssets.addAll(result);
          }
        });
      }
    } catch (e) {
      StageWhisper.lament('Failed to pick media: $e');
    }
  }

  /// 移除媒体
  void _removeAsset(int index) {
    setState(() {
      _selectedAssets.removeAt(index);
      if (_selectedAssets.isEmpty) {
        _mediaType = null;
      }
    });
  }

  /// 处理发布
  Future<void> _handlePublish(BuildContext context) async {
    // 验证登录
    final userRoom = GlobalStateProvider.userRoomOf(context);
    if (!userRoom.isLoggedIn) {
      StageWhisper.caution('Please login first');
      return;
    }

    final currentUser = userRoom.fetchCurrentUser();
    if (currentUser == null) {
      StageWhisper.caution('Please login first');
      return;
    }

    // 验证标题
    final title = _titleController.text.trim();
    if (title.isEmpty) {
      StageWhisper.caution('Please enter a title');
      return;
    }

    // 验证内容
    final content = _contentController.text.trim();
    if (content.isEmpty) {
      StageWhisper.caution('Please enter content');
      return;
    }

    setState(() {
      _isPublishing = true;
    });

    try {
      // 处理媒体文件
      final mediaUrls = <String>[];
      final thumbnailUrls = <String?>[];

      if (_selectedAssets.isNotEmpty && _mediaType == 'image') {
        // 处理图片
        for (final asset in _selectedAssets) {
          final file = await asset.file;
          if (file != null) {
            final localPath = await _copyImageToLocal(file, currentUser.id);
            if (localPath != null) {
              mediaUrls.add(localPath);
              thumbnailUrls.add(null);
            }
          }
        }
      } else if (_selectedAssets.isNotEmpty && _mediaType == 'video') {
        // 处理视频
        for (final asset in _selectedAssets) {
          final file = await asset.file;
          if (file != null) {
            final localVideoPath = await _copyVideoToLocal(
              file,
              currentUser.id,
            );
            final localThumbnailPath = await _generateVideoThumbnail(
              localVideoPath,
            );
            if (localVideoPath != null && localThumbnailPath != null) {
              mediaUrls.add(localVideoPath);
              thumbnailUrls.add(localThumbnailPath);
            }
          }
        }
      }

      // 发布动态
      final dynamicRoom = GlobalStateProvider.dynamicRoomOf(context);
      final success = dynamicRoom.publishDynamic(
        userId: currentUser.id,
        title: title,
        content: content,
        mediaUrls: mediaUrls,
        mediaType: _mediaType ?? 'text',
        thumbnailUrls: thumbnailUrls,
      );

      if (success) {
        StageWhisper.cheer('Published successfully');
        Navigator.of(context).pop();
      } else {
        StageWhisper.lament('Failed to publish');
      }
    } catch (e) {
      StageWhisper.lament('Failed to publish: $e');
    } finally {
      setState(() {
        _isPublishing = false;
      });
    }
  }

  /// 复制图片到本地
  Future<String?> _copyImageToLocal(File file, String userId) async {
    try {
      final appDir = await getApplicationDocumentsDirectory();
      final mediaDir = Directory('${appDir.path}/media/$userId/images');

      if (!await mediaDir.exists()) {
        await mediaDir.create(recursive: true);
      }

      final fileName =
          'image_${DateTime.now().millisecondsSinceEpoch}_${path.basename(file.path)}';
      final filePath = '${mediaDir.path}/$fileName';

      await file.copy(filePath);

      return filePath;
    } catch (e) {
      return null;
    }
  }

  /// 复制视频到本地
  Future<String?> _copyVideoToLocal(File file, String userId) async {
    try {
      final appDir = await getApplicationDocumentsDirectory();
      final mediaDir = Directory('${appDir.path}/media/$userId/videos');

      if (!await mediaDir.exists()) {
        await mediaDir.create(recursive: true);
      }

      final fileName =
          'video_${DateTime.now().millisecondsSinceEpoch}_${path.basename(file.path)}';
      final filePath = '${mediaDir.path}/$fileName';

      await file.copy(filePath);

      return filePath;
    } catch (e) {
      return null;
    }
  }

  /// 生成视频缩略图
  Future<String?> _generateVideoThumbnail(String? videoPath) async {
    if (videoPath == null) return null;

    try {
      final thumbnailPath = await VideoThumbnail.thumbnailFile(
        video: videoPath,
        imageFormat: ImageFormat.PNG,
        maxWidth: 200,
        quality: 75,
      );

      return thumbnailPath;
    } catch (e) {
      return null;
    }
  }
}
